package com.hua.common.commonview;


import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;

public class MyAutoRadionGroup extends LinearLayout {

	private List<Button> btList = null;
	private int normalBackRes;
	private int selectBackRes;
	private int nomalColor;
	private int selectColor;
	

	public MyAutoRadionGroup(Context context) {
		super(context);
		this.init();
	}

	public MyAutoRadionGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.init();
	}

	public MyAutoRadionGroup(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.init();
	}

	private void init() {
		this.setOrientation(HORIZONTAL);
		this.btList = new ArrayList<Button>();
		nomalColor = Color.parseColor("#ff000000");
		selectColor = Color.parseColor("#ff0085cf");
	}
	/**
	 * 设置数据
	 * @param names    数据
	 * @param normalRes  没有被选中时的背景
	 * @param selectRes  被选中时得背景资源
	 * @param defaultIndex  默认情况下选中的位置
	 * @param listener   点击时得回调
	 */
	public void setData(List<String> names, int normalRes, int selectRes,
			int defaultIndex, onSelectedListener listener) {
		this.normalBackRes = normalRes;
		this.selectBackRes = selectRes;
		this.removeAllViews();
		if (names != null) {
			this.btList.clear();
			for (int i = 0; i < names.size(); i++) {
				Button bt = new Button(getContext());
				LayoutParams params = new LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
				params.weight = 1.0f;
				if (i == defaultIndex) {
					bt.setTextColor(selectColor);
					bt.setBackgroundResource(selectRes);
				} else {
					bt.setTextColor(nomalColor);
					bt.setBackgroundResource(normalRes);
				}
				bt.setLayoutParams(params);
				bt.setText(names.get(i));
				bt.setOnClickListener(new MyonclickListener(i,listener));
				this.btList.add(bt);
				this.addView(bt);
			}
		}
	}

	/**
	 * 改变按钮的颜色
	 */
	public void changTextColor(int position) {
		for (int i = 0; i < btList.size(); i++) {
			Button bt = btList.get(i);
			if (i == position) {
				bt.setBackgroundResource(selectBackRes);
				bt.setTextColor(selectColor);
			} else {
				bt.setBackgroundResource(normalBackRes);
				bt.setTextColor(nomalColor);
			}
		}
	}

	private class MyonclickListener implements OnClickListener {
		private int position = 0;
		private onSelectedListener selectedListener = null;
		public MyonclickListener(int flog,onSelectedListener listener) {
			this.position = flog;
			this.selectedListener=listener;
		}

		@Override
		public void onClick(View arg0) {
			changTextColor(position);
			if(this.selectedListener!=null){
				this.selectedListener.onSelected(position);
			}
		}
	}

	/**
	 * 点击回调接口
	 * @author huaxiaolin_pc
	 *
	 */
	public interface onSelectedListener {
		void onSelected(int position);
	}
}

